import { ref, computed } from "vue";
import { useRoute } from "vue-router";
import { FormTypeEnum } from "@/utils/enum";
import { isEmpty, parseTime } from "@/utils/utils";
import api from "@/api/index";
import { globalEvent } from "@/main";
import {
  noContactReasonFormat,
  sourceFormat,
  varityFormResult,
  factFindingFormat,
  onsiteFormat,
  replyMethod,
  booleanFormat,
  formatAppeal,
  statusFormat,
  findingOfAuditFormat,
  formatDelayPeriod,
  applyReasonFormat,
  priorityFormat,
  levelFormat,
  priorityFormat2,
  isContactFormat,
  isStatisFied,
  isSolveFormat,
} from "@/utils/format";
import router from "@/router";
import { showToast } from "vant";
const useFormManage = () => {
  // const router = useRouter();
  /*
   * 页面类型  待办 todo 延期 delay 退单 rollback
   */
  const formType = useRoute().query.type;
  const identifer = useRoute().query.id;
  /*
   * 选择条目
   */
  const selectItem = ref({});
  //填写表单内容
  const formParams = ref({});
  //一级分类
  const class1List = ref([]);
  //二级分类
  const class2List = ref([]);
  /*
   *  ***************** 处理工单内容 *****************************
   */

  const list = computed(() => {
    const value = formParams.value;
    return [
      { title: "工单编号", content: value.workOrderNumber },
      { title: "联系人", content: value.parameter1 },
      { title: "联系电话", content: value.parameter2 },
      { title: "来电类别", content: value.wpType },
      { title: "联系地址", content: value.parameter3 },
      { title: "提交日期", content: parseTime(value.submitTime,"{y}-{m}-{d}") },
      {
        title: "12345截止日期(15个工作日)",
        content: parseTime(value.processingTimeLimit,"{y}-{m}-{d}"),
      },
      { title: "工单来源", content: sourceFormat(value.source) },
      { title: "工单优先级", content: levelFormat(value.level) },
      { title: "是否催单", content: priorityFormat(value.priority) },
      { title: "成立时间", content: parseTime(value.createTime,"{y}-{m}-{d}") },
      { title: "是否核单", content: priorityFormat2(value.priority) },
      { title: "一级分类", content: value.contentCategory },
      { title: "二级分类", content: value.contentParentCategory },
      { title: "转交日期", content: value.transmitTime },
      { title: "转交处理截止日期(14个工作日)", content: value.transmitEndTime },
      {
        title: "先行联系",
        content: isContactFormat(value.isContact),
      },

      {
        title: "未联原因",
        content: noContactReasonFormat(value.noContactReason),
      },
      { title: "12345工单内容", content:value.parameter4 },
      { title: "是否抽查", content: value.isChecks },
      { title: "抽查结果", content: value.checkResult },
    ];
  });

  //处理信息
  const manageList = computed(() => {
    return [
      {
        title: "处理类型",
        content: formParams.value.status,
        formart: statusFormat(formParams.value.status),
        type: "options",
        isRequired: true,
      },
    ];
  });

  //办结报告
  const todoReportList = () => {
    const value = formParams.value;
    return [
      {
        title: "事实认定",
        content: value.factFinding,
        formart: factFindingFormat(value.factFinding),
        type: "options",
        isRequired: true,
        maxlength: 0,
      },
      {
        title: "认定说明",
        content: value.factDescription,
        tag: "事实认定说明",
        type: "input",
        isRequired: true,
        maxlength: 50,
      },
      {
        title: "现场查看",
        content: value.onsite,
        formart: onsiteFormat(value.onsite),
        type: "options",
        isRequired: true,
        maxlength: 0,
      },
      {
        title: "诉求认定",
        content: value.appeal,
        formart: formatAppeal(value.appeal),
        type: "options",
        isRequired: true,
        maxlength: 50,
      },
      {
        title: "认定说明",
        content: value.appealDescription,
        tag: "诉求认定说明",
        type: "input",
        isRequired: true,
        maxlength: 50,
      },
      {
        title: "答复方式",
        content: value.replyMethod,
        formart: replyMethod(value.replyMethod),
        type: "options",
        isRequired: true,
        maxlength: 0,
      },
      {
        title: "答复市民时间",
        content: value.replyTime,
        formart: parseTime(value.replyTime, "{y}-{m}-{d}"),
        type: "date",
        isRequired: true,
        maxlength: 0,
      },
      {
        title: "办结日期",
        content: value.completionTime,
        formart: parseTime(value.completionTime, "{y}-{m}-{d}"),
        type: "date",
        isRequired: true,
        maxlength: 0,
      },
      {
        title: "是否解决",
        content: value.isSolve,
        formart: isSolveFormat(value.isSolve),
        type: "options",
        isRequired: true,
        maxlength: 0,
      },
      {
        title: "是否满意",
        content: value.isSatisfied,
        formart: isStatisFied(value.isSatisfied),
        type: "options",
        isRequired: true,
        maxlength: 0,
      },
      {
        title: "办结汇报",
        content: value.completionReport,
        type: "input",
        isRequired: true,
        maxlength: 300,
      },
      {
        title: "答复市民要点",
        content: value.replyHighlight,
        type: "input",
        isRequired: true,
        maxlength: 300,
      },
      {
        title: "市民反馈说明",
        content: value.feedbackExplanation,
        type: "input",
        isRequired: false,
        maxlength: 300,
      },
      {
        title: "是否拖延（3个月以上）",
        content: value.isDelay,
        formart: booleanFormat(value.isDelay),
        type: "options",
        isRequired: false,
        maxlength: 0,
      },
      {
        title: "是否拒不配合",
        content: value.isCoordinate,
        formart: booleanFormat(value.isCoordinate),
        type: "options",
        isRequired: false,
        maxlength: 0,
      },
      {
        title: "是否关门跑路",
        content: value.isRunAway,
        formart: booleanFormat(value.isRunAway),
        type: "options",
        isRequired: false,
        maxlength: 0,
      },
    ];
  };

  const delayReportList = () => {
    const value = formParams.value;
    return [
      {
        title: "申请原因",
        content: value.applyReason,
        formart: applyReasonFormat(value.applyReason),
        type: "options",
        isRequired: true,
        maxlength: 0,
      },
      {
        title: "延期期限",
        content: value.delayPeriod,
        formart: formatDelayPeriod(value.delayPeriod),
        type: "options",
        isRequired: true,
        maxlength: 0,
      },
      {
        title: "延期到期日",
        content: value.delayTime,
      },
      {
        title: "联系电话",
        content: value.phone,
        type: "input",
        isRequired: true,
        maxlength: 11,
      },
      {
        title: "经办人",
        content: value.operator,
        type: "input",
        isRequired: true,
        maxlength: 8,
      },
      {
        title: "负责人",
        content: value.head,
        type: "input",
        isRequired: true,
        maxlength: 8,
      },
      {
        title: "已用件数",
        content: value.num,
        type: "input",
        isRequired: false,
        maxlength: 8,
      },
      {
        title: "初始配额",
        content: value.quota,
        type: "input",
        isRequired: false,
        maxlength: 8,
      },
      {
        title: "备注",
        content: value.notes,
        type: "input",
        isRequired: true,
        maxlength: 50,
      },
      {
        title: "延期申请通知书",
        content: value.notice,
        type: "input",
        isRequired: false,
        maxlength: 300,
      },
    ];
  };

  //退单申请信息
  const rollbackReportList = () => {
    return [
      {
        title: "退单理由",
        content: formParams.value.returnReason,
        formart: findingOfAuditFormat(formParams.value.returnReason),
        type: "options",
        isRequired: true,
        maxlength: 0,
      },
      {
        title: "退单说明",
        content: formParams.value.returnDescription,
        type: "input",
        isRequired: true,
        maxlength: 150,
      },
    ];
  };

  const switchManageList = () => {
    let type = formParams.value.status;
    if (type == "9") {
      return todoReportList();
    } else if (type == "11") {
      return delayReportList();
    } else if (type == "13") {
      return rollbackReportList();
    } else {
      return todoReportList();
    }
  };

  /*
   * 处理工单内容标题
   */
  const reportTitle = computed(() => {
    switch (formParams.value.status) {
      case "9":
        return "办结报告";
      case "11":
        return "延期申请信息";
      case "13":
        return "退单申请信息";
      default:
        return "办结报告";
    }
  });

  /*
   *  是否选择上传组件
   */
  const showUploadfile = computed(() => {
    return formType == FormTypeEnum.TODO && (formParams.value.status == 9 || formParams.value.status == 1) ? true : false;
  });

//上传附件
const showFile = computed(() => {
  return !isEmpty(formParams.value.fileUrl)
})
const staffPhoto = ref("");
const afterRead = (file) => {
  staffPhoto.value = file.content
  console.log(file.content);
  const forms = new FormData();
  forms.append("file", file.file); // 获取上传图片信息
  api.uploadFile(forms).then((res) => {
    console.log("上传结果",res);
    formParams.value.fileUrl = res.data
  });
 };

  /*
   *  ********************************** 请求接口内容 ***************************************
   */
  const getFormDetail = () => {
    const params = {
      id: identifer,
    };

    api.institutionDetail(params).then(({ data }) => {
      // console.log("表单详情：", data);
      formParams.value = data;
      //处理初始化回显数据问题，删除初始值数据
      if (formType == FormTypeEnum.TODO) {
        formParams.value.applyReason = ""
        formParams.value.delayPeriod = ""
        formParams.value.delayTime = ""
        formParams.value.phone = ""
        formParams.value.operator = ""
        formParams.value.head = ""
        formParams.value.num = ""
        formParams.value.quota = ""
        formParams.value.notes = ""
        formParams.value.notice = ""
        formParams.value.returnDescription = ""
        formParams.value.returnReason = ""

      }
    });
  };

  //获取一级二级分类结果
  const getClassList = async (rank, id) => {
    const params = {
      rank: rank,
      parentId: id,
    };

    const { data } = await api.getOrganizationList(params);
    if (rank == 1) {
      class1List.value = data;
    } else {
      class2List.value = data;
    }
  };

  /*
   *  *************************************************************************
   */

  //选择器相关 ---------------
  /*
   *  是否显示下拉选择器
   */
  const show = ref(false);
  //当前选择时间
  const currentDate = ref(["2023", "01", "01"]);
  //显示时间选择器
  const showDate = ref(false);
  const showCalendar = ref(false);

  /*
   *  下拉选择器选择内容
   */
  const getSelectList = computed(() => {
    switch (selectItem.value.title) {
      //1.咨询类工单的事实认定：无政策信息，有政策信息，对政策解释不接受。
      // 1.意见建议类工单的事实认定：留作参考，不予采纳，部分采纳，采纳。
      // 1.投诉，求助，其他这三类工单的事实认定：属实，部分属实，不属实。
      //求助类,投诉举报类,意见建议类,咨询类,其他类
      case "事实认定":
        switch (formParams.value.wpType) {
          case "咨询类":
            return [
              { text: "无政策信息", value: "4" },
              { text: "有政策信息", value: "5" },
              { text: "对政策解释不接受", value: "6" },
            ];

          case "意见建议类":
            return [
              { text: "留作参考", value: "7" },
              { text: "不予采纳", value: "8" },
              { text: "部分采纳", value: "9" },
              { text: "采纳", value: "10" },
            ];
          default:
            //"其他类" || "求助类" || "投诉举报类"
            return [
              { text: "属实", value: "1" },
              { text: "部分属实", value: "2" },
              { text: "不属实", value: "3" },
            ];
        }

      //9.是否解决：咨询类工单的是否解决：实际解决。
      // 9.意见建议类工单的是否解决：实际解决。
      // 9.投诉，求助，其他这三类工单的是否解决：实际解决，解释说明，参考备案，诉求过高，未解决。
      case "是否拖延（3个月以上）":
      case "是否拒不配合":
      case "是否关门跑路":
        return [
          { text: "是", value: "0" },
          { text: "否", value: "1" },
        ];
      case "现场查看":
        switch (formParams.value.wpType) {
          case "咨询类":
          case "意见建议类":
            return [{ text: "无实际现场", value: "3" }];

          case "其他类":
          case "求助类":
          case "投诉举报类":
            return [
              { text: "是", value: "1" },
              { text: "否", value: "2" },
              { text: "无实际现场", value: "3" },
            ];

          default:
            return [];
        }

      case "是否解决":
        switch (formParams.value.wpType) {
          case "咨询类":
          case "意见建议类":
            return [{ text: "实际解决", value: "1" }];

          case "其他类":
          case "求助类":
          case "投诉举报类":
            return [
              { text: "实际解决", value: "1" },
              { text: "解释说明", value: "2" },
              { text: "诉求过高", value: "3" },
              // { text: "诉求过高", value: "4" },
              // { text: "未解决", value: "5" },
            ];

          default:
            return [];
        }

      // 4.投诉，求助，其他这三类工单的诉求定义：诉求合理合法，无政策依据，诉求过高，其他。意见建议类工单的诉求认定：无需认定。咨询类工单的诉求认定：无需认定。
      case "诉求认定":
        switch (formParams.value.wpType) {
          case "咨询类":
            return [{ text: "无需认定", value: "5" }];

          case "意见建议类":
            return [{ text: "无需认定", value: "5" }];
          case "其他类":
          case "求助类":
          case "投诉举报类":
            return [
              { text: "诉求合理合法", value: "1" },
              { text: "无政策依据", value: "2" },
              { text: "诉求过高", value: "3" },
              { text: "其他", value: "4" },
            ];
          default:
            //"其他类" || "求助类" || "投诉举报类"
            return [];
        }

      case "答复方式":
        return [
          { text: "电话", value: "1" },
          { text: "书面", value: "2" },
          { text: "约谈", value: "3" },
        ];
      case "是否满意":
        return [
          { text: "满意", value: "1" },
          { text: "不满意", value: "2" },
          { text: "认可", value: "3" },
          { text: "未评价", value: "4" },
        ];

      case "延期期限":
        return [
          { text: "15个自然日", value: "1" },
          { text: "30个自然日", value: "2" },
          { text: "60个自然日", value: "3" },
          { text: "90个自然日", value: "4" },
        ];

      case "申请天数":
        return [
          { text: "15个自然日", value: "1" },
          { text: "30个自然日", value: "2" },
          { text: "60个自然日", value: "3" },
          { text: "90个自然日", value: "4" },
        ];
      case "处理类型":
        return [
          { text: "处理", value: "9" },
          { text: "延期申请", value: "11" },
          { text: "退单申请", value: "13" },
        ];

      case "退单理由":
        return [
          { text: "非热线受理范围", value: "非热线受理范围" },
          { text: "非本单位职能", value: "非本单位职能" },
          { text: "非本单位辖区", value: "非本单位辖区" },
          { text: "因工单要素不全致无法处置", value: "因工单要素不全致无法处置" },
          { text: "不当重复派单", value: "不当重复派单" },
          { text: "其他", value: "其他" },
        ];
      case "审核结果":
        return [
          { text: "同意", value: "1" },
          { text: "不同意", value: "2" },
        ];

      case "满意情况":
        return [
          { text: "满意", value: "1" },
          { text: "不满意", value: "2" },
          { text: "认可", value: "3" },
          { text: "未评价", value: "4" },
        ];

      case "抽查情况":
        return [
          { text: "满意", value: "1" },
          { text: "不满意", value: "2" },
          { text: "未评价", value: "3" },
        ];

      case "申请原因":
        return [
          { text: "法定时限", value: "1" },
          { text: "特殊疑难", value: "2" },
        ];

      case "一级分类":
        return formartArr(class1List.value);

      case "二级分类":
        return formartArr(class2List.value);

      default:
        return [
          { text: "是", value: "1" },
          { text: "否", value: "2" },
        ];
    }
  });

  const formartArr = (source) => {
    let arr = [];
    source.forEach((elem) => {
      arr.push({ text: elem.name, value: elem.name, formart: elem.id });
    });
    // console.log("数据数组1", arr);
    return arr;
  };

  const formatFormParam = () => {
    const title = selectItem.value.title;
    const content = selectItem.value.content;
    const formart = selectItem.value.formart;
    const tag = selectItem.value.tag;
    if (title == "处理类型") {
      // formParams.value.handlingMethod = content;
      formParams.value.status = content;
    } else if (title == "退单理由") {
      formParams.value.returnReason = content;
    } else if (title == "退单说明") {
      formParams.value.returnDescription = content;
    } else if (title == "事实认定") {
      formParams.value.factFinding = content;
    } else if (title == "认定说明") {
      if (tag == "事实认定说明") {
        //事实认定说明
        formParams.value.factDescription = content;
      } else {
        //诉求认定说明
        formParams.value.appealDescription = content;
      }
    } else if (title == "现场查看") {
      formParams.value.onsite = content;
    } else if (title == "诉求认定") {
      formParams.value.appeal = content;
    } else if (title == "答复方式") {
      formParams.value.replyMethod = content;
    } else if (title == "答复市民时间") {
      formParams.value.replyTime = content;
    } else if (title == "办结日期") {
      formParams.value.completionTime = content;
    } else if (title == "是否解决") {
      formParams.value.isSolve = content;
    } else if (title == "是否满意") {
      formParams.value.isSatisfied = content;
    } else if (title == "办结汇报") {
      formParams.value.completionReport = content;
    } else if (title == "答复市民要点") {
      formParams.value.replyHighlight = content;
    } else if (title == "市民反馈说明") {
      formParams.value.feedbackExplanation = content;
    } else if (title == "是否拖延（3个月以上）") {
      formParams.value.isDelay = content;
    } else if (title == "是否拒不配合") {
      formParams.value.isCoordinate = content;
    } else if (title == "是否关门跑路") {
      formParams.value.isRunAway = content;
    } else if (title == "申请原因") {
      formParams.value.applyReason = content;
    } else if (title == "延期期限") {
      formParams.value.delayPeriod = content;
    }  else if (title == "联系电话") {
      formParams.value.phone = content;
    } else if (title == "经办人") {
      formParams.value.operator = content;
    } else if (title == "负责人") {
      formParams.value.head = content;
    } else if (title == "已用件数") {
      formParams.value.num = content;
    } else if (title == "初始配额") {
      formParams.value.quota = content;
    } else if (title == "备注") {
      formParams.value.notes = content;
    } else if (title == "延期申请通知书") {
      formParams.value.notice = content;
    } else if (title == "审核结果") {
      formParams.value.findingOfAudit = content;
    } else if (title == "审核意见") {
      formParams.value.confirmOpinion = content;
    } else if (title == "一级分类") {
      formParams.value["class1"] = formart;
      formParams.value["contentCategory"] = content;
    } else if (title == "二级分类") {
      formParams.value["class2"] = formart;
      formParams.value["contentParentCategory"] = content;
    } else if (title == "申请天数") {
      formParams.value["delayPeriod"] = content;
    } else if (title == "退单人员") {
      formParams.value["returnPerson"] = content;
    } else if (title == "工单编号") {
      formParams.value["workOrderNumber"] = content;
    } else if (title == "转交日期") {
      formParams.value["createTime"] = content;
    } else if (title == "申请时间") {
      formParams.value["createTime1"] = content;
    } else if (title == "退单时间") {
      formParams.value["createTime2"] = content;
    } else if (title == "申请人") {
      formParams.value["delayCreator"] = content;
    }  else if (title == "申请天数") {
      formParams.value["delayPeriod"] = content;
    } 
  };

  //提交表单内容
  const submitForm = async () => {
    if (!varityFormResult([manageList.value, switchManageList()])) {
      return;
    }

    formParams.value.orderInfoId = identifer;
    formParams.value.temporaryType = false;

    if (formParams.value.status == 1) {
      //1的待处理状态制成9
      formParams.value.status = 9;
    }

    api.institutionSubmit(formParams.value).then(() => {
      showToast("提交成功");
      formParams.value = {};
      formParams.value.formType = formType
      globalEvent.emit("myGlobalEvent", formParams.value);
      router.back();
    });
  };

  //暂存表单信息
  const saveForm = async () => {
    formParams.value.orderInfoId = identifer;
    formParams.value.temporaryType = true;
    if (formParams.value.status == 1) {
      //1的待处理状态制成9
      formParams.value.status = 9;
    }
    api.institutionSubmit(formParams.value).then(() => {
      showToast("暂存成功");
      router.back();
    });
  };

  /**
   *
   *  下拉选择器相关方法  显示下拉选择器点击事件 *******************************************
   */
  const showPick = (model) => {
    // console.log("当前选择标题:", model.title);
    selectItem.value = model;
    if (model.type == "options") {
      show.value = true;
    } else if (model.type == "date") {
      showDate.value = true;
    } else if (model.type == "calendar") {
      showCalendar.value = true;
    }
  };

  //监听输入框输入内容
  const changeInput = (model) => {
    selectItem.value = model;
    console.log("输入内容", selectItem.value.content);
    formatFormParam();
  };

  //确认选择 { selectedValues }
  const onConfirm = ({ selectedOptions, selectedValues }) => {
    // console.log("当前选择:",selectedOptions[0]);
    show.value = false;
    showDate.value = false;
    const currentV = selectedValues.join("-");

    selectItem.value.content = currentV;
    //自定义字段 - 网路请求返回的下拉框字段
    selectItem.value.formart = selectedOptions[0].formart;
    if (selectItem.value.title == "一级分类") {
      //置空二级
      formParams.value.contentParentCategory = "";
      getClassList(2, selectItem.value.formart);
    }

    formatFormParam();

    //单独处理延时到期日
    if (selectItem.value.title == "延期期限") {

        delayPeriodChange();
    }


  };


  // 延期期限选择点击事件
  const delayPeriodChange = () => {

    const delayPeriod = formParams.value.delayPeriod;
    //办理期限
    const processingTimeLimit = formParams.value.processingTimeLimit;
    if (1 == delayPeriod) {
      //15个自然日
      const date = new Date(processingTimeLimit);
      date.setDate(date.getDate() + 15);
      formParams.value.delayTime = parseTime(date, "{y}-{m}-{d}")

    } else if (2 == delayPeriod) {
      //30个自然日
      const date = new Date(processingTimeLimit);
      date.setDate(date.getDate() + 30);
      formParams.value.delayTime = parseTime(date, "{y}-{m}-{d}")

    } else if (3 == delayPeriod) {
      //60个自然日
      const date = new Date(processingTimeLimit);
      date.setDate(date.getDate() + 60);
      formParams.value.delayTime = parseTime(date, "{y}-{m}-{d}")
    } else if (4 == delayPeriod) {
      //90个自然日
      const date = new Date(processingTimeLimit);
      date.setDate(date.getDate() + 90);
      formParams.value.delayTime = parseTime(date, "{y}-{m}-{d}")
    }

  };

  const onDateConfirm = (values) => {
    const [start, end] = values;
    showCalendar.value = false;
    const currentV = [parseTime(start), parseTime(end)];
    selectItem.value.content = currentV;
    console.log("选择日期", currentV);
    formatFormParam();
  };

  //取消
  const onCancel = () => {
    show.value = false;
    showDate.value = false;
    showCalendar.value = false;
  };

  return {
    formType,
    selectItem,
    getSelectList,
    reportTitle,
    formParams,
    submitForm,
    saveForm,
    //处理表单内容
    list,
    todoReportList,
    delayReportList,
    rollbackReportList,
    showUploadfile,
    manageList,
    //下拉框内容
    show,
    showPick,
    onConfirm,
    onDateConfirm,
    onCancel,
    showDate,
    showCalendar,
    // minDate: new Date(2020, 0, 1),
    // maxDate: new Date(2025, 5, 1),
    calendarMinDate: new Date(1899, 0, 1),
    currentDate,
    getFormDetail,
    switchManageList,
    formatFormParam,
    changeInput,
    getClassList,

    //上传
    showFile,
    staffPhoto,
    afterRead
  };
};

export { useFormManage };
